import { useEffect, useState } from 'react';
import Modals from '../modals/Modals';
import { CloseOutlined, SearchOutlined } from '@ant-design/icons';
import { Input, Tabs } from 'antd';
import CheckBoxTree from './component/check-box-tree';
import datasetService from '@/api/services/datasetService';
import { GetDatasetRes } from '@/types/dataset';
import { KnowledgeListRes, KnowledgeListResList } from '@/common/types';

export type DatasetList = KnowledgeListResList & {
  children?: KnowledgeListResList[];
};

const SelectKnowModal = () => {
  const [knowValue, setKnowValue] = useState<DatasetList[]>([
    {
      id: '680cf49f0949269aef92456d',
      parent_id: null,
      team_id: '67fcd736de9ddb56bea37236',
      tmb_id: '67fcd736de9ddb56bea3723b',
      type: 'folder',
      status: 'active',
      avatar: '/imgs/files/folder.svg',
      name: 'hyl',
      vector_model: 'text-embedding-3-small',
      agent_model: 'gpt-4o-mini',
      intro: '',
      default_permission: 0,
      inherit_permission: true,
      update_time: '2025-04-26T14:58:39.181000',
      create_time: '2025-04-30T03:11:34.355872+00:00',
      metadata: {},
      openapiUrl: null,
      app_id: null,
      group_id: null,
      dataset_tags: [],
      children: [
        {
          id: '6810851d0949269aef97817f',
          parent_id: '680cf49f0949269aef92456d',
          team_id: '67fcd736de9ddb56bea37236',
          tmb_id: '67fcd736de9ddb56bea3723b',
          type: 'folder',
          status: 'active',
          avatar: '/imgs/files/folder.svg',
          name: '测试',
          vector_model: 'text-embedding-3-small',
          agent_model: 'gpt-4o-mini',
          intro: '',
          default_permission: 0,
          inherit_permission: true,
          update_time: '2025-04-29T07:51:57.499000',
          create_time: '2025-04-30T10:13:31.947566+00:00',
          metadata: {},
          openapiUrl: null,
          app_id: null,
          groupId: null,
          dataset_tags: [],
          children: [
            {
              id: '68109c6c0949269aef980b20',
              parent_id: '6810851d0949269aef97817f',
              team_id: '67fcd736de9ddb56bea37236',
              tmb_id: '67fcd736de9ddb56bea3723b',
              type: 'folder',
              status: 'active',
              avatar: '/imgs/files/folder.svg',
              name: 'Test',
              vector_model: 'text-embedding-3-small',
              agent_model: 'gpt-4o-mini',
              intro: '',
              default_permission: 0,
              inherit_permission: true,
              update_time: '2025-04-29T09:31:24.146000',
              create_time: '2025-04-30T10:13:32.956248+00:00',
              metadata: {},
              openapiUrl: null,
              app_id: null,
              groupId: null,
              dataset_tags: [],
              children: [
                {
                  id: '68109c880949269aef980d0d',
                  parent_id: '68109c6c0949269aef980b20',
                  team_id: '67fcd736de9ddb56bea37236',
                  tmb_id: '67fcd736de9ddb56bea3723b',
                  type: 'dataset',
                  status: 'active',
                  avatar: '/imgs/dataset/dataset.svg',
                  name: 'Test1',
                  vector_model: 'embedding-model',
                  agent_model: 'vllm-chat-model',
                  intro: '',
                  default_permission: 0,
                  inherit_permission: true,
                  update_time: '2025-04-29T09:31:52.475000',
                  create_time: '2025-04-30T10:13:34.289122+00:00',
                  metadata: {},
                  openapiUrl: null,
                  app_id: null,
                  groupId: null,
                  dataset_tags: [],
                },
                {
                  id: '68109c800949269aef980c6a',
                  parent_id: '68109c6c0949269aef980b20',
                  team_id: '67fcd736de9ddb56bea37236',
                  tmb_id: '67fcd736de9ddb56bea3723b',
                  type: 'dataset',
                  status: 'active',
                  avatar: '/imgs/dataset/dataset.svg',
                  name: 'Test1',
                  vector_model: 'embedding-model',
                  agent_model: 'vllm-chat-model',
                  intro: '',
                  default_permission: 0,
                  inherit_permission: true,
                  update_time: '2025-04-29T09:31:44.669000',
                  create_time: '2025-04-30T10:13:34.289241+00:00',
                  metadata: {},
                  openapiUrl: null,
                  app_id: null,
                  groupId: null,
                  dataset_tags: [],
                },
                {
                  id: '68109c780949269aef980bc7',
                  parent_id: '68109c6c0949269aef980b20',
                  team_id: '67fcd736de9ddb56bea37236',
                  tmb_id: '67fcd736de9ddb56bea3723b',
                  type: 'dataset',
                  status: 'active',
                  avatar: '/imgs/dataset/dataset.svg',
                  name: 'Test1',
                  vector_model: 'embedding-model',
                  agent_model: 'vllm-chat-model',
                  intro: '',
                  default_permission: 0,
                  inherit_permission: true,
                  update_time: '2025-04-29T09:31:36.576000',
                  create_time: '2025-04-30T10:13:34.289310+00:00',
                  metadata: {},
                  openapiUrl: null,
                  app_id: null,
                  groupId: null,
                  dataset_tags: [],
                },
              ],
            },
          ],
        },
        {
          id: '680cf4c00949269aef9245c7',
          parent_id: '680cf49f0949269aef92456d',
          team_id: '67fcd736de9ddb56bea37236',
          tmb_id: '67fcd736de9ddb56bea3723b',
          type: 'dataset',
          status: 'active',
          avatar: '/imgs/dataset/dataset.svg',
          name: '1',
          vector_model: 'embedding-model',
          agent_model: 'vllm-chat-model',
          intro: '',
          default_permission: 0,
          inherit_permission: true,
          update_time: '2025-04-26T14:59:12.517000',
          create_time: '2025-04-30T10:13:31.947652+00:00',
          metadata: {},
          openapiUrl: null,
          app_id: null,
          groupId: null,
          dataset_tags: [],
        },
      ],
    },
  ]);

  const [functionValue, setFunctionValue] = useState<DatasetList[]>([]);
  const [tabsValue, setTabsValue] = useState<string>('dataset');

  // 显式选择数据
  const [explicitCheckedValue, setExplicitCheckedValue] = useState<DatasetList[]>([]);

  // 隐式选择数据
  const [implicitCheckedValue, setImplicitCheckedValue] = useState<DatasetList[]>([]);

  useEffect(() => {
    getDataset();
  }, [tabsValue]);

  const extractChildren = (data?: DatasetList[]) => {
    let children: DatasetList[] = [];

    if (data === undefined) {
      return children;
    }

    // 遍历数组中的每一项
    for (const node of data) {
      // 将当前节点添加到结果中（如果需要，仅收集子数据可忽略此行）
      children.push(node);

      // 如果当前节点有子节点，递归提取其子节点
      if (node.children && node.children.length > 0) {
        children = children.concat(extractChildren(node.children));
      }
    }
    return children;
  };

  const filterChildren = (data: DatasetList[], value: DatasetList) => {
    let result: DatasetList[] = data;
    if (value.children) {
      const extract = extractChildren(value.children);

      for (let i = 0; i < extract.length; i++) {
        const element = extract[i];
        result = result.filter((item) => item.id !== element.id);
      }
    }
    result = result.filter((item) => item.id !== value.id);

    return [...new Set(result)];
  };

  const filterImplicit = (value: DatasetList, data: DatasetList[]) => {
    // 排除隐式选择数据
    // let result = implicitCheckedValue.filter((item) => item.id !== value.parent_id);
    // console.log(result);

    // 排除子集自身数据
    let temp = data.filter((item) => item.id !== value.id);
    // console.log(temp);

    // 合并数据
    // result = result.concat(temp);

    // const parent = implicitCheckedValue.find((item) => item.id === value.parent_id);
    // console.log('parent_id', value.parent_id);

    // console.log('implicitCheckedValue', implicitCheckedValue);

    // console.log('parent', parent);

    // if (parent && parent.parent_id) {
    //   console.log('递归了');
    //   result = filterImplicit(parent, result);
    // }

    // console.log(result);

    return temp;
  };

  const filterExplictit = (value: DatasetList, filterExp: DatasetList[]) => {
    // if (!value.parent_id) return filterExp;

    let result = filterExp.filter((item) => item.id !== value.parent_id);

    const parent = filterExp.find((item) => item.id === value.parent_id);
    if (parent && parent.parent_id !== null) {
      result = filterExplictit(parent, result);
    }

    return result;
  };

  const handleChangeCheckBox = (value: DatasetList, data: DatasetList[]) => {
    // console.log('勾选数据Data', data);
    // console.log('勾选数据Value', value);

    // 获取所有子项
    const extract = extractChildren(value.children);

    // 判断是否存在显示数据中
    const isExplicitCheckedSave = explicitCheckedValue.some((item) => item.id === value.id);

    // 判断是否存在隐式数据中
    const isImplicitChecked = implicitCheckedValue.some((item) => item.id === value.id);

    if (isExplicitCheckedSave) {
      let filterExp = filterChildren(explicitCheckedValue, value);

      let filterImp;
      if (isImplicitChecked) {
        filterImp = implicitCheckedValue.filter((item) => item.id !== value.id);
      } else {
        // filterExp = filterExp.filter((item) => item.id !== value.parent_id);
        console.log(filterExp);

        filterExp = filterExplictit(value, filterExp);
        console.log('filterExp', filterExp);

        filterImp = filterImplicit(value, data);
        // console.log('filterImp', filterImp);
      }

      setExplicitCheckedValue(filterExp);
      // setExplicitCheckedValue(filterImp);
      setImplicitCheckedValue(filterImp);
    } else {
      // 不存在显示数据中
      const result = [...explicitCheckedValue, value, ...extract];
      setExplicitCheckedValue(result);
      setImplicitCheckedValue([...implicitCheckedValue, value]);
    }
  };

  const filterParint = (parintId: string) => {};

  const checkedValue = (value: DatasetList, list: DatasetList[]) => {};

  const getDataset = () => {
    if (tabsValue === 'dataset' && knowValue.length > 0) {
      return;
    }

    if (tabsValue === 'function' && functionValue.length > 0) {
      return;
    }
  };

  const handleTreeData = (list: DatasetList[], id: string) => {
    const stack = [...knowValue]; // 模拟递归栈
    const result = [...knowValue]; // 构建最终结果

    while (stack.length > 0) {
      const current = stack.pop(); // 从栈中取出当前节点

      if (current?.id === id) {
        // 找到目标节点，更新其子节点
        current.children = list;
      }

      if (current?.children) {
        // 添加当前节点的子节点到栈
        stack.push(...current.children);
      }
    }

    return result;
  };

  const handleRequest = (value: DatasetList) => {
    datasetService
      .getDatasetList({ app_id: '', isPage: false, dataset_type: tabsValue, parentId: value.id })
      .then((res) => {
        const result = handleTreeData(res.list, value.id);
        setKnowValue(result);
      });
  };

  const handleTabs = (activeKey: string) => {
    setTabsValue(activeKey);
  };

  return (
    <Modals open={true} line={false} title={'选择xxxx可问答知识库'} width={720}>
      <div>
        <div
          className="flex h-[310px]  rounded-xl"
          style={{
            border: '1px solid #ECEEFA',
          }}
        >
          <div className="flex-1  pl-[15px]  pt-[15px]">
            <div className="pr-[22px]">
              <Input placeholder="搜索用户组、部门、或用户" prefix={<SearchOutlined />} />

              <Tabs
                defaultActiveKey="1"
                centered
                items={[
                  {
                    key: 'dataset',
                    label: '知识库文件',
                  },
                  {
                    key: 'function',
                    label: '数据接口',
                  },
                ]}
                onChange={handleTabs}
              />
            </div>
            <div className="flex h-[196px] flex-col gap-[15px] overflow-y-auto pr-[29px]">
              <CheckBoxTree
                data={tabsValue === 'dataset' ? knowValue : functionValue}
                checkedValue={explicitCheckedValue}
                onChange={handleChangeCheckBox}
                onRequest={handleRequest}
              />
            </div>
          </div>
          <div
            className="flex-1 pl-[11px] pr-[7px] pt-[23px] text-sm text-[#474C5F]"
            style={{ borderLeft: '1px solid #ECEEFA' }}
          >
            <div className="mb-[22px]">已选:{implicitCheckedValue.length}个</div>
            <div className="h-[240px] overflow-y-auto">
              {implicitCheckedValue.map((item) => (
                <div
                  key={item.id}
                  className="flex items-center justify-between py-[6px] pl-[5px] pr-[11px] hover:bg-[#D9D9D980]"
                >
                  <span>{item.name}</span>
                  <div className="cursor-pointer">
                    <CloseOutlined />
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Modals>
  );
};

export default SelectKnowModal;
